package com.yupi.yupicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.commom.BaseResponse;
import com.yupi.yupicturebackend.commom.DeleteRequest;
import com.yupi.yupicturebackend.commom.ResultUtils;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.manager.auth.SpaceUserAuthManager;
import com.yupi.yupicturebackend.model.dto.picture.PictureQueryRequest;
import com.yupi.yupicturebackend.model.dto.space.SpaceAddRequest;
import com.yupi.yupicturebackend.model.dto.space.SpaceEditRequest;
import com.yupi.yupicturebackend.model.dto.space.SpaceQueryRequest;
import com.yupi.yupicturebackend.model.dto.space.SpaceUpdateRequest;
import com.yupi.yupicturebackend.model.entity.Picture;
import com.yupi.yupicturebackend.model.entity.Space;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.SpaceLevelEnum;
import com.yupi.yupicturebackend.model.vo.SpaceLevel;
import com.yupi.yupicturebackend.model.vo.SpaceVO;
import com.yupi.yupicturebackend.service.PictureService;
import com.yupi.yupicturebackend.service.SpaceService;
import com.yupi.yupicturebackend.service.UserService;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/space")
public class SpaceController {

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private PictureService pictureService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;


    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest  request){
        ThrowUtils.throwIf(spaceAddRequest == null , ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        long id = spaceService.addSpace(spaceAddRequest, loginUser);
        return ResultUtils.success(id);
    }

    /**
     * 删除空间
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        // 校验 deleteRequest
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        // 删除空间之前查询空间是否存在
        Space space = spaceService.getById(deleteRequest.getId());
        // 空间不存在
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        // 只允许当前用户删除空间或者管理员删除空间
        User loginUser = userService.getLoginUser(request);
        spaceService.checkSpaceAuth(space, loginUser);
        // 开启事务
        // 操作数据库 删除空间 同时删除空间下的所有图片
        transactionTemplate.execute(status -> {
            // 删除空间
            boolean result = spaceService.removeById(deleteRequest.getId());
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "空间删除失败");

            PictureQueryRequest pictureQueryRequest = new PictureQueryRequest();
            pictureQueryRequest.setSpaceId(deleteRequest.getId());
            QueryWrapper<Picture> queryWrapper = pictureService.getQueryWrapper(pictureQueryRequest);
            // 根据 spaceId 删除空间下的所有图片
            boolean res = pictureService.remove(queryWrapper);
            ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR, "删除空间图片失败");
            return null;
        });

        return ResultUtils.success(true);
    }


    /**
     * 更新空间 仅管理员可用
     * @param spaceUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        // 将 dto 转为 entity
        Space space = BeanUtil.copyProperties(spaceUpdateRequest, Space.class);
        // 校验空间信息是否合法
        spaceService.validSpace(space, false);
        // 自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 更新空间之前判断空间是否存在
        Space oldSpace = spaceService.getById(space.getId());
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 更新空间
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "空间更新失败");
        return ResultUtils.success(true);
    }


    /**
     * 根据 id 获取空间
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVoById(long id, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);

        return ResultUtils.success(spaceVO);
    }

    /**
     * 根据 id 获取空间 仅管理员可用
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/get")
    public BaseResponse<Space> getSpaceById(long id, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(space);
    }


    /**
     * 分页获取空间列表
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(spaceQueryRequest ==  null, ErrorCode.PARAMS_ERROR);
        long pageSize = spaceQueryRequest.getPageSize();
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR); // 防止爬虫爬取所有数据
        // 构造 queryWrapper
        QueryWrapper<Space> queryWrapper = spaceService.getQueryWrapper(spaceQueryRequest);
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(spaceQueryRequest.getCurrent(), pageSize), queryWrapper);
        // 封装VO对象
        Page<SpaceVO> spacePageVO = spaceService.getSpaceVOPage(spacePage, request);
        // 获取封装类
        return ResultUtils.success(spacePageVO);
    }

    /**
     * 分页获取空间列表 （仅管理员可用）
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        // 校验参数
        ThrowUtils.throwIf(spaceQueryRequest ==  null, ErrorCode.PARAMS_ERROR);
        long pageSize = spaceQueryRequest.getPageSize();
        // 构造 queryWrapper
        QueryWrapper<Space> queryWrapper = spaceService.getQueryWrapper(spaceQueryRequest);
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(spaceQueryRequest.getCurrent(), pageSize), queryWrapper);
        // 获取封装类
        return ResultUtils.success(spacePage);

        /*long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spacePage);*/
    }

    /**
     * 编辑空间
     * @param spaceEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(spaceEditRequest ==  null || spaceEditRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        // 将 dto 转为 entity
        Space space = BeanUtil.copyProperties(spaceEditRequest, Space.class);
        // 自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        space.setEditTime(new Date()); // 设置编辑时间
        // 校验 空间信息是否合法
        spaceService.validSpace(space,false);
        // 更新前查看数据库是否存在该空间
        Space oldSpace = spaceService.getById(space);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验更新权限 仅当前用户或管理员可编辑
        User loginUser = userService.getLoginUser(request);
        spaceService.checkSpaceAuth(space, loginUser);
        // 更新数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "空间编辑失败");

        return ResultUtils.success(true);
    }

    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> getSpaceLevelList(){
        SpaceLevelEnum[] values = SpaceLevelEnum.values(); // 获取所有枚举
        List<SpaceLevel> spaceLevelList = Arrays.stream(values)
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()
                ))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }

}
